package com.ksyun.campus.dataserver.controller;

import com.ksyun.campus.dataserver.domain.Result;
import com.ksyun.campus.dataserver.services.DataService;
import com.ksyun.campus.dataserver.services.RegistService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController("/")
public class DataController {

    @Autowired
    RegistService registService;

    @Autowired
    DataService dataService;

    /**
     * 1、读取request content内容并保存在本地磁盘下的文件内
     * 2、同步调用其他ds服务的write，完成另外2副本的写入
     * 3、返回写成功的结果及三副本的位置
     *
     * @param fileSystemName
     * @param path
     * @param offset
     * @param length
     * @return
     */
    @RequestMapping("write")
    public Result writeFile(@RequestHeader String fileSystemName,
                            @RequestParam String path,
                            @RequestParam(required = false) Integer offset,
                            @RequestParam(required = false) Integer length,
                            @RequestPart("fileContent") MultipartFile file) {

         return dataService.write(fileSystemName,path,offset,length,file);
    }

    /**
     * 在指定本地磁盘路径下，读取指定大小的内容后返回
     *
     * @param fileSystemName
     * @param path
     * @param offset
     * @param length
     * @return
     */
    @RequestMapping("read")
    public Result<byte[]> readFile(@RequestHeader String fileSystemName,
                                           @RequestParam String path,
                                           @RequestParam(required = false) Integer offset,
                                           @RequestParam(required = false) Integer length) {

        return dataService.read(fileSystemName,path,offset,length);
    }

    /**
     * 关闭退出进程
     */
    @RequestMapping("shutdown")
    public void shutdownServer() {

        System.exit(-1);
    }
}
